<template>
  <view class="u-page">
    <view class="cell-page">
      <view class="u-page__item">
        <text class="u-page__item__title">基础信息</text>
        <u-cell-group>
          <u-cell title="集资参与人姓名" :value="form.name" v-if="oneself"></u-cell>
          <u-cell title="继承权利人姓名" :value="form.name1" v-if="!oneself"></u-cell>
          <u-cell title="集资参与人证件号" :value="form.idCardNo" v-if="oneself"></u-cell>
          <u-cell title="继承权利人证件号" :value="form.idCard1No" v-if="!oneself"></u-cell>
          <u-cell title="集资参与人银行卡号" :value="form.bankCardNo" v-if="oneself"></u-cell>
          <u-cell title="继承权利人银行卡号" :value="form.bankCard1No" v-if="!oneself"></u-cell>
          <u-cell title="联系电话" :value="form.contactNumber"></u-cell>
        </u-cell-group>
      </view>
      <view class="u-page__item" v-if="form.resultList[0].type == 1">
        <text class="u-page__item__title">集资信息</text>
        <u-cell-group v-if="form.resultList[0]">
          <!-- <u-cell title="实际投入金额" :value="formatNum(form.actualInvestmentAmount)"></u-cell>
          <u-cell title="实际返本利金额" :value="formatNum(form.actualAmountOfPrincipalAndInterestReturned)"></u-cell> -->
		  <u-cell title="实缴本金" :value="formatNum(form.resultList[0].principal)"></u-cell>
		  <u-cell title="实缴股金" :value="formatNum(form.resultList[0].shareCapital)"></u-cell>
		  <u-cell title="付息金额" :value="formatNum(form.resultList[0].interestPayment)"></u-cell>
		  <u-cell title="还本金额" :value="formatNum(form.resultList[0].repaymentOfPrincipal)"></u-cell>
          <u-cell title="实际损失金额" :value="formatNum(form.resultList[0].actualLossAmount)"></u-cell>
          <u-cell title="实际应返还损失额" :value="formatNum(form.resultList[0].actualAmountOfLossToBeReturned)"></u-cell>
        </u-cell-group>
      </view>
    </view>
    <u-row class="w-100 mt-4" justify="center">
      <u-col span="5" justify="center">
        <u-button shape="circle" :disabled="form.resultList[0].type == 4 && form.resultList[0].state == 2" @click="toPreSrPage"><view>上一步</view></u-button>
      </u-col>
      <u-col span="5" justify="center">
        <u-button type="primary" shape="circle" @click="signTipShow = true"><view>拍照核验</view></u-button>
      </u-col>
    </u-row>
    <u-row class="mt-4">
      <u-col span="12"><uni-steps :options="stepList" :active="currentStepIndex"></uni-steps></u-col>
    </u-row>
    <u-popup :show="signShow" :round="10" mode="center"><Autograph ref="sign" @back="confirm"></Autograph></u-popup>
	<view>
	  <u-modal :show="tipShow" title="温馨提示">
	    <view>
	      <view class="font-tip">{{ tipText }}</view>
	    </view>
	
	    <u-button slot="confirmButton" @click="tipShow = false" type="success" shape="circle">已知晓</u-button>
	  </u-modal>
	</view>
	<view>
	  <u-modal :show="signTipShow" showCancelButton title="温馨提示" @confirm="goSign" @cancel="signTipShow = false">
	    <view>
	      <view class="font-tip">{{ signTipText }}</view>
	    </view>
		<!-- <u-button slot="confirmButton" @click="goSign" type="success" shape="circle">确定</u-button>
		<u-button slot="confirmButton" @click="signTipShow = false" type="success" shape="circle">取消</u-button> -->
	  </u-modal>
	</view>
  </view>
</template>

<script>
import { baseFont, srStepKey } from '@/common/config.js';
import { getAccessToken, getVerifyToken, updateImageToRepository, realNameAuth, match } from '@/common/baiduApi.js';
import Autograph from '@/component/autograph/autograph.vue';
import { pathToBase64 } from 'image-tools';
import { formatReserve } from '@/util/common.js';
import { checkSave } from '@/common/api/srRegister.js';

export default {
  components: {
    Autograph,
  },
  data() {
    return {
      preStep: srStepKey.step2,
      currentStep: srStepKey.step3,
      nextStep: srStepKey.step3,
      labelStyle: { fontSize: baseFont + 'upx', marginBottom: '20upx' },
      form: {
        name: null,
        idCardNo: null,
        idCardPositiveUrl: null,
        idCardFaceUrl: null,
        idCardBackUrl: null,
        bankCardPositiveUrl: null,
        bankCardBackUrl: null,
        bankCardNo: null,
        name1: null,
        idCard1No: null,
        idCard1PositiveUrl: null,
        idCard1FaceUrl: null,
        idCard1BackUrl: null,
        bankCard1PositiveUrl: null,
        bankCard1BackUrl: null,
        bankCard1No: null,
        deathCertificateUrl: null,
        acts: null,
        relation: null,
        registeredResidence: [],
        bills: [],
        videoUrl: null,
        videoFaceUrl: null,
        sign: null,
        oneself: true,
        sign: null,
        contactNumber: null,
        caseList: [],
		address: null
      },
      signShow: false,
      cardFaceBase64: '',
	  tipShow: false,
	  tipText: '请确保是集资参与人本人操作，并不要处在强光或弱光环境下。',
	  signTipShow: false,
	  signTipText: '如您对以上信息无异议，请点击确认按钮；若有异议，请点击取消按钮。'
    };
  },
  computed: {
    currentStepIndex() {
      return this.oneself ? 2 : 3;
    },
  },
  onLoad(options) {
	  
    this.checkSrPage(options);
    const { index = {}, step0_5 = {}, step1 = {}, step2 = {}, step1_5 = {} } = this.$getSrInfo(this.idCard);
    this.form = {
      ...this.form,
      ...index,
      ...step1,
      ...step2,
    };
    // 办理人逻辑判断
    if (this.oneself) {
      this.cardFaceBase64 = step1.idCardFaceBase64;
    } else {
      this.cardFaceBase64 = step1_5.idCard1FaceBase64;
      this.form = {
        ...this.form,
        ...step1_5,
      };
    }
    const { resultList = [] } = index;
	this.form.id = resultList[0].id
	this.form.turnWhite = resultList[0].turnWhite
    if (resultList.length === 0) {
      this.toSrIndex();
    }
    // 白名单
    if (resultList[0].type === 1) {
      this.form.caseList=resultList.map(item=>{return {cid:item.cid}})
    } else if (resultList[0].type === 2 || resultList[0].type === 3) {
      this.toSrIndex();
    } else {
      // 数据补录
      this.form.caseList=step0_5.resultList
    }
	
	if (resultList[0].turnWhite) {
		 uni.request({
			url: resultList[0].idCardFaceUrl,
			method: 'GET',
			responseType: 'arraybuffer',
			success: async res => {
				let base64 = wx.arrayBufferToBase64(res.data); 
				this.cardFaceBase64 = base64;
			}
		});
	}

    if (options.check && options.check == this.form.check ) {
		if (resultList[0].type == 1) {
			let that = this;
			
			//关闭页面滚动，
			that.stop();
			
			that.signShow = true;
			that.$nextTick(() => {
			  that.$refs.sign.autograph();
			});
		} else if(resultList[0].type == 4){
			checkSave(this.form).then(res => {
			  const cid=this.form.caseList.map(item=>item.cid).join(',')
			  this.toSrResult(res.data.state, res.data.reason, this.idCard,cid);
			});
		}
    } 
	else {
		this.tipShow = true;
	}
  },
  methods: {
    // 阻止页面滚动
    stop() {
      var box = function(e) {
        passive: false;
      };
      document.body.style.overflow = 'hidden';
      document.addEventListener('touchmove', box, false);
    },
    // 允许页面滚动
    move() {
      var box = function(e) {
        passive: false;
      };
      document.body.style.overflow = ''; // 出现滚动条
      document.removeEventListener('touchmove', box, false);
    },
    formatNum(num) {
      if (num) {
        return formatReserve(num);
      } else {
        return null;
      }
    },
    confirm(bool) {
      // 签名结束，放开页面滚动
      this.move();

      this.signShow = false;
      if (bool) {
        this.form.sign = this.$refs.sign.signature;
        checkSave(this.form).then(res => {
          const cid=this.form.caseList.map(item=>item.cid).join(',')
          this.toSrResult(res.data.state, res.data.reason, this.idCard,cid);
        });
      }
    },
    doSign() {
      let that = this;
      that.signShow = true;
      that.$nextTick(() => {
        that.$refs.sign.autograph();
      });
    },
    async goSign() {
		this.signTipShow = false
      const idCard = this.idCard;
      this.saveSrInfo(idCard);
      let that = this;
      that.accessToken = await getAccessToken();
      that.verifyToken = await getVerifyToken(that.accessToken);
      that.face1 = this.cardFaceBase64.replace(/^data:image\/\w+;base64,/, '');
      // let imgRes = await updateImageToRepository(baseImage, accessToken, verifyToken);
      setTimeout(() => {
        uni.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['camera'],
          success(res) {
            // uni.$u.toast('选择完图片');
            uni.showLoading({
              title: '处理中，请稍后...',
            });
            let file = res.tempFiles[0];
            if (file.size > 1024 * 1024 * 4) {
              that.compressImage(file);
            } else {
              const tempFilePaths = res.tempFilePaths;
              pathToBase64(tempFilePaths[0]).then(path => {
                that.baseImage2 = path.replace(/^data:image\/\w+;base64,/, '');
                if (that.baseImage2) {
                  // uni.$u.toast('1比1');
                  that.goMath(that.face1, that.baseImage2);
                }
              });
            }
          },
          fail: error => {
            uni.$u.toast(JSON.stringify(error));
          },
        });
      });
    },
    goMath(face1, face2) {
      let that = this;
      match(face1, face2, that.accessToken).then(res => {
        if (res.data.error_code == 0) {
          // uni.$u.toast('一比一');
          uni.showLoading({
            title: '正在人像一比一，请稍后...',
          });
          if (res.data.result.score >= 60) {
            that.uploadImgRepo(face2);
          }
        } else {
          uni.$u.toast('请确保本人操作！');
        }
      });
    },
    uploadImgRepo(base64) {
      // uni.$u.toast('入库');
      uni.showLoading({
        title: '正在人像入库，请稍后...',
      });
      let that = this;
      const sucess = this.getSrBaiduSuccessPage(this.form.check);
      updateImageToRepository(base64, that.accessToken, that.verifyToken).then(imgRes => {
        if (imgRes.data.success) {
          uni.$u.toast('打开活体检测');
          realNameAuth(that.verifyToken, sucess, '');
        } else {
          uni.$u.toast(imgRes.data.message);
        }
      });
    },
    compressImage(urlData) {
      // uni.$u.toast('压缩');
      // uni.showLoading({
      // 	title: '压缩中...'
      // })
      uni.showLoading({
        title: '正在压缩人像，请稍后...',
      });
      let _this = this;
      uni.getImageInfo({
        src: urlData.path,
        success(res) {
          let originWidth = res.width; //图片原始宽
          let originHeight = res.height; //图片原始高
          let maxWidth = 800;
          let maxHeight = 800;
          let img = new Image();
          img.src = res.path;
          let canvas = document.createElement('canvas');
          let ctx = canvas.getContext('2d');
          // 目标尺寸
          let targetWidth = originWidth;
          let targetHeight = originHeight;
          if (originWidth > maxWidth || originHeight > maxHeight) {
            if (originWidth / originHeight > maxWidth / maxHeight) {
              // 更宽，按照宽度限定尺寸
              targetWidth = maxWidth;
              targetHeight = Math.round(maxWidth * (originHeight / originWidth));
            } else {
              targetHeight = maxHeight;
              targetWidth = Math.round(maxHeight * (originWidth / originHeight));
            }
          }

          canvas.width = targetWidth;
          canvas.height = targetHeight;
          // 图片压缩
          ctx.drawImage(img, 0, 0, targetWidth, targetHeight);
          // canvas对图片进行缩放 0.3是我定义的图片质量，
          let base64 = canvas.toDataURL(urlData.type, 0.3);

          // uni.hideLoading()
          _this.goMath(_this.face1, base64.split(',')[1]);
        },
        fail() {
          uni.showModal({
            title: '提示',
            content: '图片压缩失败',
            showCancel: false,
          });
        },
      });
    },
  },
};
</script>

<style scoped lang="scss">
.cell-page {
  padding-bottom: 20px;
}
</style>
